package com.ming.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ming.exception.DeptException;
import com.ming.mapper.DeptMapper;
import com.ming.mapper.EmpMapper;
import com.ming.pojo.entity.Dept;
import com.ming.pojo.vo.DeptListVO;
import com.ming.pojo.dto.DeptQueryDTO;
import com.ming.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * 部门服务实现类
 */
@Slf4j
@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }

    @Override
    public PageInfo<DeptListVO> pageQuery(DeptQueryDTO deptQueryDTO) {
        log.info("开始分页查询部门数据，页码: {}, 每页条数: {}", deptQueryDTO.getPageNum(), deptQueryDTO.getPageSize());

        // 设置分页参数
        PageHelper.startPage(deptQueryDTO.getPageNum(), deptQueryDTO.getPageSize());

        // 执行条件查询
        List<DeptListVO> deptListVO = deptMapper.listVOByCondition(deptQueryDTO);

        // 获取分页信息
        PageInfo<DeptListVO> pageInfo = new PageInfo<>(deptListVO);

        log.info("分页查询完成，总记录数: {}, 总页数: {}, 当前页记录数: {}",
                pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getList().size());

        return pageInfo;
    }

    @Override
    public Dept getById(Integer id) {
        if (id == null || id <= 0) {
            throw DeptException.notFound("部门ID无效");
        }

        Dept dept = deptMapper.getById(id);
        if (dept == null) {
            throw DeptException.notFound("部门不存在，ID: " + id);
        }

        return dept;
    }

    @Override
    public void add(Dept dept) {
        // 参数校验
        validateDeptForAdd(dept);

        // 检查部门名称是否重复
        checkDeptNameExists(null, dept.getName());

        // 设置时间
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());

        try {
            deptMapper.insert(dept);
            log.info("部门添加成功，名称: {}", dept.getName());
        } catch (Exception e) {
            log.error("部门添加失败，部门信息: {}", dept, e);
            throw DeptException.of("部门添加失败：" + e.getMessage(), e);
        }
    }

    @Override
    public void update(Dept dept) {
        // 参数校验
        validateDeptForUpdate(dept);

        // 检查部门是否存在
        Dept existingDept = deptMapper.getById(dept.getId());
        if (existingDept == null) {
            throw DeptException.notFound("部门不存在，ID: " + dept.getId());
        }

        // 检查部门名称是否重复（排除自己）
        if (!Objects.equals(existingDept.getName(), dept.getName())) {
            checkDeptNameExists(dept.getId(), dept.getName());
        }

        // 更新时间
        dept.setUpdateTime(LocalDateTime.now());

        try {
            deptMapper.update(dept);
            log.info("部门更新成功，ID: {}, 名称: {}", dept.getId(), dept.getName());
        } catch (Exception e) {
            log.error("部门更新失败，部门信息: {}", dept, e);
            throw DeptException.of("部门更新失败：" + e.getMessage(), e);
        }
    }

    @Override
    public void deleteById(Integer id) {
        if (id == null || id <= 0) {
            throw DeptException.notFound("部门ID无效");
        }

        // 检查部门是否存在
        Dept dept = deptMapper.getById(id);
        if (dept == null) {
            throw DeptException.notFound("部门不存在，ID: " + id);
        }

        // 检查部门下是否有员工
        int empCount = empMapper.countByDeptId(id);
        if (empCount > 0) {
            throw DeptException.hasEmployees(
                String.format("部门 '%s' 下还有 %d 名员工，无法删除", dept.getName(), empCount));
        }

        try {
            deptMapper.deleteById(id);
            log.info("部门删除成功，ID: {}, 名称: {}", id, dept.getName());
        } catch (Exception e) {
            log.error("部门删除失败，ID: {}", id, e);
            throw DeptException.of("部门删除失败：" + e.getMessage(), e);
        }
    }

    // ========== 私有方法 ==========

    /**
     * 校验新增部门参数
     */
    private void validateDeptForAdd(Dept dept) {
        if (dept == null) {
            throw DeptException.of("部门信息不能为空");
        }

        if (!StringUtils.hasText(dept.getName())) {
            throw DeptException.of("部门名称不能为空");
        }

        if (dept.getName().length() > 50) {
            throw DeptException.of("部门名称长度不能超过50个字符");
        }

            }

    /**
     * 校验更新部门参数
     */
    private void validateDeptForUpdate(Dept dept) {
        if (dept == null) {
            throw DeptException.of("部门信息不能为空");
        }

        if (dept.getId() == null || dept.getId() <= 0) {
            throw DeptException.of("部门ID无效");
        }

        if (!StringUtils.hasText(dept.getName())) {
            throw DeptException.of("部门名称不能为空");
        }

        if (dept.getName().length() > 50) {
            throw DeptException.of("部门名称长度不能超过50个字符");
        }

            }

    /**
     * 检查部门名称是否存在
     */
    private void checkDeptNameExists(Integer excludeId, String name) {
        Dept existingDept = deptMapper.getByName(name);
        if (existingDept != null && !Objects.equals(existingDept.getId(), excludeId)) {
            throw DeptException.nameExists("部门名称 '" + name + "' 已存在");
        }
    }

    }
